<template>
  <div class="app-container">
    <div class="title">修改密码</div>
    <div class="formbox">
      <el-form ref="ruleForm" label-position="left" label-width="80px" :model="formLabelAlign" :rules="rules" >
        <el-form-item label="原密码" prop="password">
          <el-input v-model="formLabelAlign.password" type="password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="formLabelAlign.newPassword" type="password" placeholder="请输入新密码"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword">
          <el-input v-model="formLabelAlign.rePassword" type="password" placeholder="请再次输入密码"/>
        </el-form-item>
        <el-form-item align="center">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Userupdate',
  data() {
    const repassValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.formLabelAlign.newPassword) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    return {
      formLabelAlign: {
        password: '',
        newPassword: '',
        rePassword: ''
      },
      rules: {
        password: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        rePassword: [
          { validator: repassValidator, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const res = await this.$http.post('/cms/admin/changePass', { ...this.formLabelAlign })
          if (res.code === 0) {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            await this.$store.dispatch('user/logout')
            this.$router.push(`/login?redirect=${this.$route.fullPath}`)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
